//
//  SmallVideoDetailController.m
//  OnionHome
//
//  Created by fengjie on 2019/9/29.
//  Copyright © 2019 FengJie. All rights reserved.
//

#import "SmallVideoDetailController.h"

#import "CLPlayerView.h"

@interface SmallVideoDetailController ()<UICollectionViewDelegate,UICollectionViewDataSource, UIScrollViewDelegate,CLCollectionViewDetaiCellDelegate>
/**<#属性#>*/
@property (nonatomic,strong)UICollectionView*listView;
/**<#属性#>*/
@property (nonatomic,strong) UICollectionViewFlowLayout * layout;

/**CLplayer*/
@property (nonatomic, weak) CLPlayerView *playerView;
/**记录Cell*/
@property (nonatomic, assign) UICollectionViewCell *cell;
/**输入框*/
@property (nonatomic,strong)UITextField*textField;
/**<#属性#>*/
@property (nonatomic,strong)NSMutableArray*loadArray;
/**<#属性#>*/
@property (nonatomic,strong)PubulicInputToolbar*inputToolbar;
@end

@implementation SmallVideoDetailController

-(void)dealloc{
    //销毁播放器
    [self.playerView destroyPlayer];
    self.playerView = nil;
    self.cell = nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createNavView];
    self.automaticallyAdjustsScrollViewInsets = NO;
//    self.view.backgroundColor = UIColorFromRGB(0x363647);
    UIView * view = [self createTexFileView];
    
    [self.view addSubview:self.listView];
    [self.view addSubview:view];
    [self.view addSubview:self.inputToolbar];

    
    [self.listView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-50);
    }];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.top.mas_equalTo(self.listView.mas_bottom).offset(6);
        make.bottom.mas_equalTo(-6);
    }];

}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setNavBarBackgroundAndClearColor];
    [UIApplication sharedApplication].statusBarHidden = YES;
    [self setIQKeyboardManagerEnable:NO];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self setNavBarBackgroundAndNotClearColor];
    [UIApplication sharedApplication].statusBarHidden = NO;
    [self setIQKeyboardManagerEnable:YES];

}
-(void)createNavView{
    [self addNavigationItemWithImageNames:@[@"sangedian1"] isLeft:NO target:self action:@selector(rightAction) tags:nil];
    [self addNavigationItemWithImageNames:@[@"back1"] isLeft:YES target:self action:@selector(backBtnClicked) tags:nil];
}
-(void)rightAction{
    [self.view endEditing:YES];
    PresentationObject * object = [PresentationObject sharedPresentationObject];
    object.subViewFrame = CGRectZero;
    [object showPresentingViewController:self PresentedViewController:[ShareViewController new]];
}
-(void)setIndexxPath:(NSIndexPath *)indexxPath{
    _indexxPath = indexxPath;
    DLogFunc;
}
-(void)cl_tableViewCellPlayVideoWithCell:(SmallVideoDetailCell *)cell{
    //记录被点击的Cell
    _cell = cell;
    //销毁播放器
    [_playerView destroyPlayer];
    CLPlayerView *playerView = [[CLPlayerView alloc] initWithFrame:CGRectZero];
    playerView.maskView.playBottomToolBar.hidden = YES;
    playerView.maskView.playButton.hidden = YES;
    _playerView = playerView;
    [cell.playerBgView addSubview:_playerView];
    
    self.playerView.maskView.userInteractionEnabled = YES;
    [self.playerView.maskView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)]];
    
    [playerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    //    //重复播放，默认不播放
        _playerView.repeatPlay = YES;
    //    //当前控制器是否支持旋转，当前页面支持旋转的时候需要设置，告知播放器
//        _playerView.isLandscape = YES;
    //    //设置等比例全屏拉伸，多余部分会被剪切
    //    _playerView.fillMode = ResizeAspectFill;
    //设置进度条背景颜色
    _playerView.progressBackgroundColor = [UIColor colorWithRed:53 / 255.0 green:53 / 255.0 blue:65 / 255.0 alpha:1];
    //设置进度条缓冲颜色
    _playerView.progressBufferColor = [UIColor grayColor];
    //设置进度条播放完成颜色
    _playerView.progressPlayFinishColor = UIColorFromRGB(0x009966);
    //视频地址
    _playerView.url = [NSURL URLWithString:cell.model.videoUrl];
    //播放
    [_playerView playVideo];
    //返回按钮点击事件回调
    [_playerView destroyPlay:^{
        cell.stopPlay = YES;
        DLog(@"播放器被销毁了");
    }];
    [_playerView backButton:^(UIButton *button) {
        DLog(@"返回按钮被点击");
    }];
    //播放完成回调
//    kWeakSelf(weakSelf);
    [_playerView endPlay:^{
        //销毁播放器
//        [weakSelf.playerView destroyPlayer];
//        weakSelf.playerView = nil;
//        weakSelf.cell = nil;
        DLog(@"播放完成");
    }];

}
#pragma mark ---UICollectionViewDelegate,UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    SmallVideoDetailCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass(SmallVideoDetailCell.class) forIndexPath:indexPath];
//    cell.model = self.dataArray[indexPath.row];
    cell.delegate = self;
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
}
-(void)tapAction{
    [self.view endEditing:YES];
//    [self.inputToolbar bounceToolbar];

}
//cell将要出现的时候调用
-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    SmallVideoDetailCell * myCell = (SmallVideoDetailCell *)cell;
    myCell.model = self.dataArray[indexPath.row];
    DLogFunc;
    if (self.indexxPath) {
        [self.listView scrollToItemAtIndexPath:self.indexxPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
        self.indexxPath = nil;
    }
    
    if (!self.indexxPath) {
        myCell.stopPlay = NO;
        [self cl_tableViewCellPlayVideoWithCell:myCell];
//        if (self.dataArray.count - indexPath.row <=3) {
//            DLog(@"添加更多数据");
//            [self.dataArray addObjectsFromArray:self.loadArray];
//            [self.listView reloadData];
//        }
    }
}
//cell离开tableView时调用
-(void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    //因为复用，同一个cell可能会走多次
    if ([_cell isEqual:cell]) {
        //区分是否是播放器所在cell,销毁时将指针置空
        [_playerView destroyPlayer];
        _cell = nil;
    }
    
    DLogFunc;
}
#pragma mark  定义每个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(KScreenWidth,  KScreenHeight-50);
}
// 列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
// 行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

#pragma mark ---懒加载
-(UICollectionView *)listView{
    if (!_listView) {
        self.layout= [[UICollectionViewFlowLayout alloc] init];
        self.layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _listView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.layout];
        _listView.backgroundColor=KWhiteColor;
        _listView.delegate=self;
        _listView.dataSource = self;
        _listView.scrollEnabled = YES;
        _listView.bounces = NO;
        _listView.pagingEnabled = YES;
        [_listView registerClass:[SmallVideoDetailCell class] forCellWithReuseIdentifier:NSStringFromClass(SmallVideoDetailCell.class)];
        if (@available(iOS 11.0, *)) {
            _listView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _listView;
}

-(UITextField*)textField{
    if(!_textField){
        _textField=[UITextField new];
        _textField.placeholder = @"写评论…";
        _textField.enabled = NO;
    }
    return _textField;
}
-(UIView * )createTexFileView{
    UIView * view = UIView.new;
    view.backgroundColor = UIColor.whiteColor;
    
    UIView * view1 = UIView.new;
    view1.backgroundColor = UIColorFromRGB(0xF5F7F5);
    ViewRadius(view1, 4);
    view1.userInteractionEnabled = YES;
    
    [view1 addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(inputAction)]];
    
    [view addSubview:view1];
    
    
    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.centerY.mas_equalTo(0);
        make.height.mas_equalTo(30);
    }];
    
    UIImageView * leftImage = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"xiepinglun")];
    [view1 addSubview:leftImage];
    [view1 addSubview:self.textField];
    
    [leftImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.left.mas_equalTo(8);
        make.width.height.mas_equalTo(20);
    }];
    
    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.left.mas_equalTo(leftImage.mas_right).offset(5);
        make.top.right.bottom.mas_equalTo(0);
    }];
    
    return view;
}
-(void)inputAction{
    [self.inputToolbar popToolbar];
}
-(PubulicInputToolbar*)inputToolbar{
    if(!_inputToolbar){
        _inputToolbar=[[PubulicInputToolbar alloc] init];
        _inputToolbar.textViewMaxLine = 3;
        _inputToolbar.fontSize = 18;
        _inputToolbar.placeholder = @"写评论...";
        _inputToolbar.isTop = YES;

        kWeakSelf(weakSelf);
        [_inputToolbar inputToolbarSendText:^(NSString * _Nonnull text) {
            // 清空输入框文字
            [weakSelf.inputToolbar bounceToolbar];
        }];
    }
    return _inputToolbar;
}
-(NSMutableArray *)loadArray{
    if (!_loadArray) {
        _loadArray = [[NSMutableArray alloc] init];
        NSData *JSONData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"XSPDate" ofType:@"json"]];
        NSArray *array = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingAllowFragments error:nil];
        [array enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            PlayModel *model = [PlayModel new];
            [model setValuesForKeysWithDictionary:obj];
            [_loadArray addObject:model];
        }];
    }
    return _loadArray;
}
@end


@interface SmallVideoDetailCell ()
/**视频图片*/
@property (nonatomic,strong)UIImageView * IMGView;
/**标题*/
@property (nonatomic,strong)UILabel * titleLabel;
/**播放按钮*/
@property (nonatomic,strong)UIButton * stopBtn;
/**用户头像*/
@property (nonatomic,strong)UIImageView*userImage;
/**用户名称*/
@property (nonatomic,strong)UILabel*userLabel;
/**关注按钮*/
@property (nonatomic,strong)UIButton*guanBtn;
/**点赞*/
@property (nonatomic,strong)CustomButton*zanBtn;
/**消息*/
@property (nonatomic,strong)CustomButton*xiaoxiBtn;
/**转发*/
@property (nonatomic,strong)CustomButton*zhuanfaBtn;

@end

@implementation SmallVideoDetailCell

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self createUI];
    }
    return self;
}
-(void)createUI{
   self.IMGView = UIImageView.new;
   self.IMGView.userInteractionEnabled = YES;
   
   self.playerBgView = UIView.new;
   self.playerBgView.userInteractionEnabled = YES;
   self.playerBgView.hidden = YES;

   [self addSubview:self.IMGView];
   [self addSubview:self.playerBgView];
    [self addSubview:self.userImage];
    [self addSubview:self.userLabel];
    [self addSubview:self.guanBtn];
    [self addSubview:self.titleLabel];
    [self addSubview:self.zhuanfaBtn];
    [self addSubview:self.xiaoxiBtn];
    [self addSubview:self.zanBtn];

    [self.IMGView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    [self.playerBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.bottom.mas_equalTo(self.IMGView);
    }];
//    [self.IMGView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(playAction)]];
    
    [self.userImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
        make.bottom.mas_equalTo(-44);
        make.width.height.mas_equalTo(40);
    }];
    [self.userLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.userImage.mas_right).offset(12);
        make.centerY.mas_equalTo(self.userImage);
    }];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.userImage);
        make.bottom.mas_equalTo(self.userImage.mas_top).offset(-16);
    }];
    [self.guanBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.userLabel.mas_right).offset(12);
        make.centerY.mas_equalTo(self.userImage);
        make.width.mas_equalTo(56);
        make.height.mas_equalTo(26);
    }];
    [self.zhuanfaBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-16);
        make.bottom.mas_equalTo(-52);
        
    }];
    [self.xiaoxiBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.zhuanfaBtn);
        make.bottom.mas_equalTo(self.zhuanfaBtn.mas_top).offset(-26);
        
    }];
    [self.zanBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.zhuanfaBtn);
        make.bottom.mas_equalTo(self.xiaoxiBtn.mas_top).offset(-26);
        
    }];

}

-(UILabel*)titleLabel{
    if(!_titleLabel){
        _titleLabel=[UILabel new];
        _titleLabel.textColor = KWhiteColor;
        _titleLabel.font = SYSTEMFONT(16);
        _titleLabel.text = @"教你做美味沙拉酱";
    }
    return _titleLabel;
}
-(UIImageView*)userImage{
    if(!_userImage){
        _userImage=[UIImageView new];
        _userImage.layer.cornerRadius = 20;
        _userImage.layer.masksToBounds=YES;
        _userImage.image = IMAGE_NAMED(@"userIconDefut");
        _userImage.image = [Utilis getRandomUserImage];
        _userImage.userInteractionEnabled = YES;
        [_userImage addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(userAction)]];


    }
    return _userImage;
}
-(UILabel*)userLabel{
    if(!_userLabel){
        _userLabel=[UILabel new];
        _userLabel.textColor = KWhiteColor;
        _userLabel.font = PingFangSC_Medium(18);
        _userLabel.text = @"我是大鲨鱼";
        _userLabel.userInteractionEnabled = YES;
        [_userLabel addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(userAction)]];

    }
    return _userLabel;
}
-(UIButton*)guanBtn{
    if(!_guanBtn){
        _guanBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        [_guanBtn setTitle:@"关注" forState:UIControlStateNormal];
        [_guanBtn setTitle:@"已关注" forState:UIControlStateSelected];
        [_guanBtn setBackgroundImage:[UIImage createImageWithColor:UIColorFromRGB(0x009966)] forState:UIControlStateNormal];
    }
    return _guanBtn;
}
-(CustomButton*)zanBtn{
    if(!_zanBtn){
        _zanBtn=[CustomButton buttonWithTitle:@"232" Image:@"小视频_zan"];
        _zanBtn.titleColor = KWhiteColor;
    }
    return _zanBtn;
}
-(CustomButton*)xiaoxiBtn{
    if(!_xiaoxiBtn){
        _xiaoxiBtn=[CustomButton buttonWithTitle:@"232" Image:@"小视频_xiaoxi"];
        _xiaoxiBtn.titleColor = KWhiteColor;
        _xiaoxiBtn.userInteractionEnabled = YES;
        [_xiaoxiBtn addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(xiaoxiAction)]];

    }
    return _xiaoxiBtn;
}
-(CustomButton*)zhuanfaBtn{
    if(!_zhuanfaBtn){
        _zhuanfaBtn=[CustomButton buttonWithTitle:@"232" Image:@"小视频_zhuanfa"];
        _zhuanfaBtn.titleColor = KWhiteColor;
        _zhuanfaBtn.userInteractionEnabled = YES;
        [_zhuanfaBtn addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(shareAction)]];
    }
    return _zhuanfaBtn;
}

-(void)setModel:(PlayModel *)model{
    _model = model;
    [self.IMGView imageViewWithUrl:model.pictureUrl placeholderImage:@"dynamicDefut"];
    DLogFunc;
}

- (void)setStopPlay:(BOOL)stopPlay{
    _stopPlay = stopPlay;
    self.playerBgView.hidden = stopPlay;
}
- (void)playAction {
    self.playerBgView.hidden = NO;
    if (_delegate && [_delegate respondsToSelector:@selector(cl_tableViewCellPlayVideoWithCell:)]){
        [_delegate cl_tableViewCellPlayVideoWithCell:self];
    }
}
-(void)userAction{
    PersonalHomePageBasseController * vc = [[PersonalHomePageBasseController alloc] init];
    vc.type = PersonalHomePageTA;
    [[self getCurrentViewController].navigationController pushViewController:vc animated:YES];

}
-(void)xiaoxiAction{
    PresentationObject * objcet = [PresentationObject sharedPresentationObject];
    objcet.subViewFrame = CGRectMake(0, 225, KScreenWidth, KScreenHeight - 225);
//    objcet.alpha_bgView = 1;
    [objcet showPresentingViewController:[self getCurrentViewController] PresentedViewController:[HomeCommentsController new]];

}
-(void)shareAction{
    [[self getCurrentViewController] presentViewController:[[BasseNavigationController alloc]initWithRootViewController:[ForwardingController new]] animated:YES completion:nil];

}
@end
